package Avocado.visual {

	import Avocado.util.MoveObject;
	
	import com.greensock.TweenMax;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.filters.ColorMatrixFilter;
	
	public class PhotoChange extends MovieClip {
		
		public var photoList:Array = new Array;
		
		private var mvLoader:AssetLoader;
		
		public function PhotoChange(_photoList:Array) {
			super();
			
			this.photoList = _photoList;
			
			this.addEventListener(Event.ADDED_TO_STAGE, initThis);
		}

		private function initThis(e:Event):void{
			this.removeEventListener(Event.ADDED_TO_STAGE, initThis);
			
			setupMvLoader();
			setupPhoto();
		}

		
		private function setupMvLoader():void{
			mvLoader = new AssetLoader;
			mvLoader.x = 252;
			mvLoader.y = 200;
			addChild(mvLoader);
		}
			private function removeMvLoader():void{
				removeChild(mvLoader);
				mvLoader = null;
			}
		
		
		/**
		 * 
		 * ***/
		private function setupPhoto():void{
			for (var a:int=0; a<photoList.length; a++){
				var foto:SpriteImage = new SpriteImage(photoList[a].src, 16);
				foto.x = Math.random()*8 + 5; 
				foto.y = Math.random()*8 + 10;
				foto.rotation = Math.random()*4 -1;
				foto.visible = false;
				foto.addEventListener(Event.COMPLETE, photoComplete(a));
				
				photoList[a].mv = foto;
				addChild(foto);
			}
		}
			private function photoComplete(i:int):Function{
				return function(e:Event):void{
					e.currentTarget.visible = true;
					if (i == photoList.length-1){
						allPhotosComplete();
					}
				}
			}

			private function allPhotosComplete():void{
				removeMvLoader();
				for (var a:int=0; a<photoList.length; a++){
					photoList[a].mv.removeEventListener(Event.COMPLETE, photoComplete);
				}
			}
		
		
		/**
		 * 
		 * ***/
		public function moveToLeft():void{
			var selected:Object = new Object;
			selected = photoList.shift();
			photoList.push(selected);
			
			reorderList();
		}


		/**
		 * 
		 * ***/
		public function moveToRight():void{
			var selected:Object = new Object;
			selected = photoList.pop();
			photoList.splice(0,0,selected);
			
			reorderList();
		}
		
		
		/**
		 * 
		 * ***/
		private function reorderList():void{
			for (var s:* in photoList){
				var mvObj:Object = new Object;
				if (s == photoList.length-1){
					var matrix:Array = new Array;
					matrix = matrix.concat([2, 0, 0, 0, 0]); // red
					matrix = matrix.concat([0, 2, 0, 0, 0]); // green
					matrix = matrix.concat([0, 0, 2, 0, 0]); // blue
					matrix = matrix.concat([0, 0, 0, 1, 0]); // alpha
					photoList[s].mv.filters = [new ColorMatrixFilter(matrix)];

					mvObj.x = Math.random()*8 + 5;
					mvObj.y = Math.random()*8 + 10;
					mvObj.rotation = Math.random()*4 -1;

					mvObj.colorMatrixFilter = {brightness:1};

				} else {
					mvObj.x = Math.random()*8 + 5;
					mvObj.y = Math.random()*8 + 10;
					mvObj.rotation = Math.random()*4 -1;
				}

				TweenMax.to(photoList[s].mv, .6, mvObj);
				addChild(photoList[s].mv);
			}

		}

		
		

	}
}